/** platformConnector.js
*
*   Provides the functionality for the gadget to run on different platforms
*   without changing the Sourcecode.
*
*   When the constructor is called it checks the availability of platform-specific
*   variables. Depending on the platform some methods of the PlatformConnector are
*   bound. The remaining methods are bound with the function "empty" which does
*   nothing and returns "false".
*
**/

var prefs;

function PlatformConnector(){

    //Bind the Sidebar-specific functions
    if(typeof(System) != "undefined"){
        PlatformConnector.prototype.saveSettings = saveSettingsVista;
        PlatformConnector.prototype.loadSettings = loadSettingsVista;
        PlatformConnector.prototype.isDocked = isDockedVista;
        PlatformConnector.prototype.beginTransition = beginTransitionVista;
        PlatformConnector.prototype.endTransition = endTransitionVista;
        PlatformConnector.prototype.onSettingsClosed = onSettingsClosedVista;
        PlatformConnector.prototype.flyoutShow = FlyoutShowVista;
        PlatformConnector.prototype.onUndock = onUndockVista;
        PlatformConnector.prototype.onDock = onDockVista;
        PlatformConnector.prototype.settingsUI = settingsUIVista;
        PlatformConnector.prototype.getData = getDataVista;
        PlatformConnector.prototype.getWeatherData = getWeatherDataVista;
        PlatformConnector.prototype.getWeatherSearch = getWeatherSearchVista;
        PlatformConnector.prototype.setBackgroundPNG = setBackgroundPNGVista;
        PlatformConnector.prototype.setImage = setImageVista;
        PlatformConnector.prototype.makePageView = makePageViewVista;
        PlatformConnector.prototype.setFlyoutFile = setFlyoutFileVista;
        PlatformConnector.prototype.onFlyoutShow = onFlyoutShowVista;
        PlatformConnector.prototype.setDimensionsLarge = setDimensionsVista;
        
    //Bind the IGoogle-specific functions
    } else if(typeof(gadgets) != "undefined"){
        prefs = new _IG_Prefs();
        PlatformConnector.prototype.saveSettings = saveSettingsIGoogle;
        PlatformConnector.prototype.loadSettings = loadSettingsIGoogle;
        PlatformConnector.prototype.getData = getDataIGoogle;
        PlatformConnector.prototype.getWeatherData = getWeatherDataIGoogle;
        PlatformConnector.prototype.getWeatherSearch = getWeatherSearchIGoogle;
        PlatformConnector.prototype.setImage = setImageWeb;
        PlatformConnector.prototype.makePageView = makePageViewIGoogle;
        PlatformConnector.prototype.setDimensionsLarge = setDimensionsWeb;
    
    //Binds the Netvibes ("Universal Widgets API") specific functions    
    } else if(typeof(widget) != "undefined"){
        PlatformConnector.prototype.saveSettings = saveSettingsUWA;
        PlatformConnector.prototype.loadSettings = loadSettingsUWA;
        PlatformConnector.prototype.getData = getDataUWA;
        PlatformConnector.prototype.getWeatherData = getWeatherDataUWA;
        PlatformConnector.prototype.getWeatherSearch = getWeatherSearchUWA;
        PlatformConnector.prototype.setImage = setImageWeb;
        PlatformConnector.prototype.makePageView = makePageViewIGoogle;
        PlatformConnector.prototype.setDimensionsLarge = setDimensionsWeb;
    }
    
    //Check if some of the methods are not bound and bind them
    if(!PlatformConnector.prototype.saveSettings)
        PlatformConnector.prototype.saveSettings = empty;
    
    if(!PlatformConnector.prototype.loadSettings)
        PlatformConnector.prototype.loadSettings = empty;
    
    if(!PlatformConnector.prototype.isDocked)  
        PlatformConnector.prototype.isDocked = empty;
        
    if(!PlatformConnector.prototype.getData)
        PlatformConnector.prototype.getData = empty;
    
    if(!PlatformConnector.prototype.beginTransition)
        PlatformConnector.prototype.beginTransition = empty;
    
    if(!PlatformConnector.prototype.endTransition)
        PlatformConnector.prototype.endTransition = empty;
    
    if(!PlatformConnector.prototype.onSettingsClosed)
        PlatformConnector.prototype.onSettingsClosed = empty;
    
    if(!PlatformConnector.prototype.flyoutShow)
        PlatformConnector.prototype.flyoutShow = empty;
        
    if(!PlatformConnector.prototype.onUndock)
        PlatformConnector.prototype.onUndock = empty;
    
    if(!PlatformConnector.prototype.onDock)
        PlatformConnector.prototype.onDock = empty;
    
    if(!PlatformConnector.prototype.settingsUI)
        PlatformConnector.prototype.settingsUI = empty;
        
    if(!PlatformConnector.prototype.getWeatherData)
        PlatformConnector.prototype.getWeatherData = empty;
        
    if(!PlatformConnector.prototype.getWeatherSearch)
        PlatformConnector.prototype.getWeatherSearch = empty;
        
    if(!PlatformConnector.prototype.setBackgroundPNG)
        PlatformConnector.prototype.setBackgroundPNG = empty;
        
    if(!PlatformConnector.prototype.setImage)
        PlatformConnector.prototype.setImage = empty;
        
    if(!PlatformConnector.prototype.makePageView)
        PlatformConnector.prototype.makePageView = empty;
        
    if(!PlatformConnector.prototype.setFlyoutFile)
        PlatformConnector.prototype.setFlyoutFile = empty;
        
    if(!PlatformConnector.prototype.onFlyoutShow)
        PlatformConnector.prototype.onFlyoutShow = empty;
        
    if(!PlatformConnector.prototype.setDimensionsLarge)
        PlatformConnector.prototype.setDimensionsLarge = empty;
    
};

//Dummy function, which is applied when the given functionality is not available
function empty(){
    return false;
}

/***************************************
            Vista version
***************************************/

function saveSettingsVista(name, value){
    System.Gadget.Settings.write(name, value);
}

function loadSettingsVista(name){
    return System.Gadget.Settings.read(name);
}

function isDockedVista(){
    return System.Gadget.docked;
}

function beginTransitionVista(){
    System.Gadget.beginTransition();
}

function endTransitionVista(timeTransition){
    System.Gadget.endTransition(System.Gadget.TransitionType.none, timeTransition);
}

function onSettingsClosedVista(funct){
    System.Gadget.onSettingsClosed = funct;
}

function onUndockVista(funct){
    System.Gadget.onUndock = funct;
}

function onDockVista(funct){
    System.Gadget.onDock = funct;
}

function FlyoutShowVista(){
    if(arguments.length == 1){
        if(System.Gadget.Flyout.show != arguments[0])
            System.Gadget.Flyout.show = arguments[0];
    }
    
    return System.Gadget.Flyout.show;
}

function settingsUIVista(document){
    System.Gadget.settingsUI = document;
}

function getDataVista(url){
    var rssObj = new ActiveXObject("Msxml2.XMLHTTP");
    rssObj.open("GET", url, true);
    rssObj.onreadystatechange = function() {
        if (rssObj.readyState === 4) {
            if (rssObj.status === 200) {
                var rssXML = rssObj.responseXML;
                News.processData(rssXML);
            } else {
                News.showError(rssObj.status);
            }
        } else {
        
        }
    }
    
    rssObj.send(null);
}

//Generates a pageview at our tracking-partner
function makePageViewVista(counter){

    var linkURL = MSNWidget.preview_link[counter];
    if(linkURL.indexOf('?') != -1)linkURL += "&ocid="+ocid_pv;
    else linkURL += "?ocid="+ocid_pv;
    
    if(document.getElementById("tracking") == null){
        var tag = document.createElement("script");
        tag.type="text/javascript";
        tag.src = "http://estj.msn.com/br/om/js/s_code.js";
        tag.id = 'tracking';
        document.body.appendChild(tag);
    }
    
    var page = new ActiveXObject("Msxml2.XMLHTTP");
    page.open("GET", linkURL, true);
    page.onreadystatechange = function() {
        if(page.readyState == 4){
            if(page.status == 200){
                var response = page.responseText;
                
                var url = evalPageview(response, linkURL);
            
                var rssObj = new ActiveXObject("Msxml2.XMLHTTP");
                rssObj.open("GET", url, true);
                rssObj.onreadystatechange = function() {
                    if(rssObj.readyState == 2){
                    }
                }
                rssObj.send(null);                
            }
        }
    }
    page.send(null);
         
}

function getWeatherDataVista(url){
    var rssObj = new ActiveXObject("Msxml2.XMLHTTP");
    rssObj.open("GET", url, true);
    rssObj.onreadystatechange = function() {
        if (rssObj.readyState === 4) {
            if (rssObj.status === 200) {
                var rssXML = rssObj.responseXML;
                Weather.GetWeatherData(rssXML, "C");
                Weather.save();
                Weather.showSmallWeather();
                if(Weather.visible)
                    Weather.showWeather();
                else Weather.show(false);
                Weather.loading(false);
            } else {
                Weather.loading(false);
            }
        } else {
            Weather.loading(false);
        }
    }
    rssObj.send(null);
}

function getWeatherSearchVista(url){
    var rssObj = new ActiveXObject("Msxml2.XMLHTTP");
    rssObj.open("GET", url, true);
    rssObj.onreadystatechange = function() {
        if (rssObj.readyState === 4) {
            if (rssObj.status === 200) {
                Weather.loading(false);
                var rssXML = rssObj.responseXML;
                Weather.getLocationData(rssXML);
                //Weather.showWeather();
            } else {
                Weather.loading(false);
            }
        } else {
            
        }
    }
    rssObj.ontimeout
    rssObj.send(null);
}

function setBackgroundPNGVista(src){ 
   System.Gadget.background = src;
}

function setImageVista(url, counter){
    // Retrieve a reference to the plug-in.
    var slPlugin = MSNWidget.root.getHost();
    var downloader = slPlugin.createObject("downloader");

    downloader.addEventListener("completed", function(sender){GUI.Content.Events.downloader(sender, counter)});
    downloader.addEventListener("DownloadFailed", function(sender){
    MSNWidget.root.findName("news_img_"+counter).Source = config.image_str + "default/"+News.getCategory()+".jpg";
    MSNWidget.root.findName("news_img_refl_"+counter).Source = config.image_str + "default/"+News.getCategory()+".jpg";

        GUI.Content.Events.downloader(null, counter);
    });
    
    downloader.open("GET", url);
    downloader.send();
}

function setFlyoutFileVista(url){
    System.Gadget.Flyout.file = url;
}

function onFlyoutShowVista(fnct){
    System.Gadget.Flyout.onShow = fnct;
}

function setDimensionsVista(){
    with (document.body.style) {
        width = 385;
        height = 280;
    }
    document.getElementById("MSNSilverlight").style.width = "385px";
    document.getElementById("MSNSilverlight").style.height = "280px";
}

/**************************************************
            IGoogle Version 
**************************************************/
function saveSettingsIGoogle(name, value){
    prefs.set(name, value);
}

function loadSettingsIGoogle(name, type){
    var result;
    switch(type){
      case "String": result = prefs.getString(name);break;
      
      case "bool": result = prefs.getBool(name);break;
      
      default: result = prefs.getString(name);break;
    }

    if(result == "")return false;
    else return result;
}

function getDataIGoogle(url){
        
    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM;
    gadgets.io.makeRequest(url, function(response) {
            News.processData(response.data);
        }, params);
}

function getWeatherDataIGoogle(url){

    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM;
    gadgets.io.makeRequest(url, function(response) {
        Weather.GetWeatherData(response.data, "C");
        Weather.save();
        Weather.showWeather();
        Weather.showSmallWeather();
        Weather.loading(false);
      }, params);
}

function getWeatherSearchIGoogle(url){

    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM;
    gadgets.io.makeRequest(url, function(response) {
        Weather.getLocationData(response.data);
        Weather.showWeather();
      }, params);
}

function setImageIGoogle(link, counter){
    MSNWidget.root.findName("news_img_"+counter).Source = link;
    MSNWidget.root.findName("news_img_refl_"+counter).Source = link;
    GUI.Content.Events.downloader(null, counter);
}

function makePageViewIGoogle(counter){

    var linkURL = MSNWidget.preview_link[counter];
    if(linkURL.indexOf('?') != -1)linkURL += "&ocid="+ocid_pv;
    else linkURL += "?ocid="+ocid_pv;
    
    if(document.getElementById("tracking") == null){
        var tag = document.createElement("script");
        tag.type="text/javascript";
        tag.src = "http://estj.msn.com/br/om/js/s_code.js";
        tag.id = 'tracking';
        document.body.appendChild(tag);
    }
    
    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
    gadgets.io.makeRequest(linkURL, function(reponse, linkURL){igoogleCallback(reponse, linkURL);}, params);         
}

//helperfunction for the google-specific ajax calls
function igoogleCallback(response, linkURL){

    var url = evalPageview(response.text, linkURL);

    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
    gadgets.io.makeRequest(url, null, params);                
}

function setDimensionsWeb(){
    document.getElementById("MSNSilverlight").style.width = "100%";
    document.getElementById("MSNSilverlight").style.height = "100%";
    document.body.stlye.width = "100%";
}


/**************************************************
            IGoogle Version 
**************************************************/
function saveSettingsUWA(name, value){
    widget.setValue(name, value);
}

function loadSettingsUWA(name, type){
    var result;
    switch(type){
      case "String": result = widget.getValue(name);break;
      
      case "bool": result = widget.getBool(name);break;
      
      default: result = widget.getValue(name);break;
    }

    if(result == "" || result == null)return false;
    else return result;
}

function getDataUWA(url){

    UWA.Data.request(
        url,
        {
            method: 'get',
            proxy: 'ajax',
            type: 'xml',
            cache: 3600,
            onComplete: News.processData
        });
}

function getWeatherDataUWA(url){
      
      UWA.Data.request(
        url,
        {
            method: 'get',
            proxy: 'ajax',
            type: 'xml',
            cache: 3600,
            onComplete: function(response) {
                Weather.GetWeatherData(response, "C");
                Weather.save();
                Weather.showWeather();
                Weather.showSmallWeather();
                Weather.loading(false);
              }
        });
}

function getWeatherSearchUWA(url){

      UWA.Data.request(
        url,
        {
            method: 'get',
            proxy: 'ajax',
            type: 'xml',
            cache: 3600,
            onComplete: function(response) {
                Weather.getLocationData(response.data);
                Weather.showWeather();
              }
        });  
}

function makePageViewUWA(counter){

    var linkURL = MSNWidget.preview_link[counter];
    if(linkURL.indexOf('?') != -1)linkURL += "&ocid="+ocid_pv;
    else linkURL += "?ocid="+ocid_pv;
    
    if(document.getElementById("tracking") == null){
        var tag = document.createElement("script");
        tag.type="text/javascript";
        tag.src = "http://estj.msn.com/br/om/js/s_code.js";
        tag.id = 'tracking';
        document.body.appendChild(tag);
    }
    
    UWA.Data.request(
        linkURL,
        {
            method: 'get',
            proxy: 'ajax',
            type: 'text',
            cache: 3600,
            onComplete: function(response, linkURL){UWACallback(response, linkURL);}
        });           
}

//helperfunction for the google-specific ajax calls
function UWACallback(response, linkURL){

    var url = evalPageview(response, linkURL);

    UWA.Data.request(
        url,
        {
            method: 'get',
            proxy: 'ajax',
            type: 'xml',
            cache: 3600,
            onComplete: null
        });                 
}



/*********************************************
*       GENERIC FUNCTIONS
*********************************************/
function setDimensionsWeb(){
    document.getElementById("MSNSilverlight").style.width = "385px";
    document.getElementById("MSNSilverlight").style.height = "280px";
}

function setImageWeb(link, counter){
    MSNWidget.root.findName("news_img_"+counter).Source = link;
    MSNWidget.root.findName("news_img_refl_"+counter).Source = link;
    GUI.Content.Events.downloader(null, counter);
}

function evalPageview(response, linkURL){
    //Limit the response to the tracking-div
    response = '<div ' + response.substring(response.indexOf('id="omni"'));
    response = response.substring(0, response.indexOf('</div>')+6);
    
    //Read out the s_account
    response = response.substring(response.indexOf("s_account")+11) ;
    var s_account = response.substring(0, response.indexOf(";")-1);
    
    //Read out the configurations
    var config_js = response.substring(response.indexOf("s.linkInternal"));
    config_js = config_js.substring(0, config_js.indexOf("s_code=s.t();")+14);
    
    
    eval(config_js);
    s.prop50 = linkURL;
    var s_code = s.t();
    var url = s_code.substring(s_code.indexOf('src="')+5);
    url = url.substring(0, url.indexOf('"'));
    
    //Rework the parameter "g"
    var g = url.substring(url.indexOf("&g=")+3);
    g = g.substring(g.indexOf("&"));
    url = url.substring(0, url.indexOf("&g=")+3) + escape(linkURL) + g;
    
    //Rework the parameter "c29"
    var c29 = url.substring(url.indexOf("&c29=")+5);
    c29 = c29.substring(c29.indexOf("&"));
    var shortUrl = linkURL.substring(0, linkURL.indexOf("?"));
    url = url.substring(0, url.indexOf("&c29=")+5) + shortUrl + c29;
    
    return url;
}